global class UrlRewriter implements Site.UrlRewriter 
{

	//Variables to represent my custom Visualforce pages that display page information
	String FRANCHISE_HOME_PAGE = '/franchisehome?referrerCode=';
	// The first global method for mapping external URL to an internal one
	
	global PageReference mapRequestUrl(PageReference requestUrl)
	{
	    String url = requestUrl.getUrl().substring(1, requestUrl.getUrl().length());
	    //Now check this against a franchise, to see if it matches the friendlyUrl property of the franchise account
	    //if so we are going to dynamically generate a franchise home page.
	    try
	    {
	    	Account franchise = [Select referrerCode__c from Account where friendlyUrl__c = :url];
	    	System.debug('Franchise code -> ' + franchise.referrerCode__c);
	    	PageReference pageReference = new PageReference(FRANCHISE_HOME_PAGE + franchise.referrerCode__c);
	    	pageReference.setRedirect(true);
	    	return pageReference;
	    }
	    catch(System.Exception e)
	    {
	    	return null;
	    }
	}
	
	global List<PageReference> generateUrlFor(List<PageReference> myForcedotcomUrls) 
	{
		return null;
	}
	
	static testMethod void testThis()
	{
		RecordType recordType = [Select id From RecordType Where Name = 'Franchisee'];
        Account account = new Account(recordtypeid=recordType.id);
        account.friendlyUrl__c = 'test';
        account.name = 'Giles';
        Database.insert(account);
		PageReference pageReference = new PageReference('/test');
		UrlRewriter urlRewriter = new UrlRewriter();
		PageReference result = urlRewriter.mapRequestUrl(pageReference);
		System.debug(result.getUrl());
		System.assert(result.getUrl().contains(UrlRewriter.FRANCHISE_HOME_PAGE));
		pageReference = new PageReference('/false');
		System.assert(urlRewriter.mapRequestUrl(pageReference) == null);
		System.assert(urlRewriter.generateUrlFor(null) == null);
		
	}
	
}